/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//var xmlHttp;
/**
 * get XMLHttpRequest object
 */
function getXMLObject() {
    var xmlHttpObj;
    try {
        xmlHttpObj = new XMLHttpRequest(); // for Mozilla, Opera 8.0+, Safari ... browsers
    }catch(e){
        try {
            xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP"); // for old Microsoft browsers
        } catch (e2){
            xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP"); // for Microsoft IE 6.0+
        }
    }

    return xmlHttpObj;
}

function ajaxAddToCart(id, name, desc, price){
    var URL = "../cart/add_cart.html?product.id=" + id + "&product.name=" + name + "&product.description=" + desc + "&product.price=" + price;
    var xmlHttp = getXMLObject();

    xmlHttp.onreadystatechange = updateNumberItems(xmlHttp);

    xmlHttp.open("GET", URL, true);

    xmlHttp.send(null);
}

function checkProductQuantity(){
    var xmlHttp = getXMLObject();
    if(xmlHttp){
        var url = "../cart/checkout.html?ajax=true";
        xmlHttp.open("POST", url, true);

        // tell the server that you're sending XML type
        xmlHttp.setRequestHeader("Content-Type", "text/xml");

        var cartXML = convertProductToXML(cartObj.items);

        xmlHttp.send(cartXML);

        // callback function
        xmlHttp.onreadystatechange = updateCartObjFromSever(cartObj, xmlHttp);
    }
}

//function updateCartObjFromSever(obj, xmlHttp){
//    if(!obj) {
//        return;
//    }
//
//    if(xmlHttp.readyState == 4) {
//        if(xmlHttp.status == 200) {
//            // do something
//            alert('aaaaaaaaaavvvvvvvvvvvvdddddddd');
//            alert(xmlHttp.responseXML);
//        }
//    }
//}

function updateNumberItems(){
    if(xmlHttp.readyState == 4){
        document.getElementById('numberCartItems').innerHTML = xmlHttp.responseText;
    }
}

/*
 * Delete an category in admin category management page using AJAX.
 */
function deleteCategoryAjax(btnDeleteNode) {
    var btnValue = btnDeleteNode.value;
    var isDelete = "true";
    if(btnValue == "Hidden") {
        isDelete = "true";
    }else{
        isDelete = "false";
    }

    var trNode = btnDeleteNode.parentNode.parentNode;
    var id = trNode.getElementsByTagName('td')[0].innerHTML.trim();
    var xmlHttp = getXMLObject();
    if(xmlHttp){
        var url = "../admin/deleteCategory.html?id=" + id + "&isDeleted=" + isDelete;
        xmlHttp.open("POST", url, true);

        xmlHttp.send(null);

        // callback function
        xmlHttp.onreadystatechange = function () {
            updateDeletedCategoryCallback(xmlHttp, trNode, isDelete, btnDeleteNode);
        }
    }
}

function updateDeletedCategoryCallback(xmlHttp, trNode, isDelete, btnDeleteNode) {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            if(isDelete == "true") {
                btnDeleteNode.value = "Visible";
                toggleDeteledCheckBox(trNode, xmlHttp.responseText, true);
            }else{
                btnDeleteNode.value = "Hidden";
                toggleDeteledCheckBox(trNode, xmlHttp.responseText, false);
            }
        }
    }
}

/*
 * Toggle relative category when deleted or undeleted main categories to sub categories.
 */
function toggleDeteledCheckBox(rowNode, stringIds, toggleValue) {
    try{
        if(!stringIds || stringIds.trim() == "error") {
            console.log("Some thing error in server when delete category using AJAX!");
            window.location.href = "../error/error.html";
        }
        
        var tbody = rowNode.parentNode;
        var rows = tbody.getElementsByTagName('tr');
        var ids = stringIds.trim().split(' ');
        var id;
        for (var i = 0; i < rows.length; i++) {
            id = rows[i].getElementsByTagName('td')[0].innerHTML.trim();
            for (var j = 0; j < ids.length; j++) {
                if(id == Number(ids[j])) {
                    // update checkbox
                    rows[i].getElementsByTagName('td')[3].childNodes[0].checked = toggleValue;

                    // update value for button
                    if(toggleValue == true) {
                        rows[i].getElementsByTagName('td')[5].childNodes[0].value = "Visible";
                    }else{
                        rows[i].getElementsByTagName('td')[5].childNodes[0].value = "Hidden";
                    }

                    // remove that element from array ids
                    ids.splice(j, 1);
                    j--;
                }
            }

            // check if ids length is 0, then no need to continue loop
            if(ids.length == 0 ) {
                break;
            }
        }

    }catch(er) {
        console.log(er);
    }
}

/**
 * Called after index page has loaded, get DOM tree from server
 * and store in an variable of js in client for using search product suggestion.
 */
function loadProductsXmlFromServer(){
    var xmlHttp = getXMLObject();
    if(xmlHttp){
        var url = "../product/searchProductXMLCallback.html";
        xmlHttp.open("POST", url, true);

        xmlHttp.send(null);

        // callback function
        xmlHttp.onreadystatechange = function () {
            getProductsXMLCallback(xmlHttp);
        }
    } else{
        alert('Your browser not support AJAX!');
    }
}

var xmlDoc;

/**
 * Store response DOM tree of products in client.
 */
function getProductsXMLCallback(xmlHttp) {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            xmlDoc = xmlHttp.responseXML;
        }
    }
}

/**
 * Called when onkeyup of search product textbox, handle to display suggesstion.
 */
function searchProductAjax(e) {
    var value = document.getElementById('input-search').value;
    if(value == "") {
        document.getElementById("search-product-suggest").innerHTML = "";
        return;
    }

    // max display suggest item 
    var maxDisplay = 5;
    var sugguestClass = "sugguest-item";
    var hoverClass = "selected";
    var suggestBox = document.getElementById("search-product-suggest");

    // check that if user press key down - up - escapse - enter, then no need
    // to search in DOM anymore, just handle key event
    if(!updateSelectedItem(e, suggestBox, sugguestClass, hoverClass, maxDisplay)) {
        return;
    }

    //    var nsResolver = xmlDoc.createNSResolver(xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
    //    var express = "//product[contains(./name,'" + value + "')]";
    //    var iterator = xmlDoc.evaluate(express, xmlDoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

    // check have loaded DOM tree of products.xml from response finish or not yet.
    if(!xmlDoc) {
        return;
    }

    // get product tag in DOM products.xml tree.
    var productTags = xmlDoc.getElementsByTagName('product');
    if(productTags.length == 0) {
        return;
    }

    var id = "";
    var name = "";
    try {
        //        var thisNode = iterator.iterateNext();

        // contains item in html code
        var items = new Array();

        // add suggest <a> tag to suggest box.
        for (var i = 0; i < productTags.length; i++) {
            var childNodes = productTags[i].childNodes;
            id = productTags[i].attributes.getNamedItem("id").nodeValue;

            // check if product is deleted, not add to suggested
            if(productTags[i].getElementsByTagName('isdeleted')[0].textContent.trim() == "true") {
                continue;
            }
            
            for (var j = 0; j < childNodes.length; j++) {
                var node = childNodes[j];
                if(node.nodeName.trim() == "name") {
                    var nodeValue = node.textContent.trim();
                    console.log('value = ' + value + ' to lowercase = ' +  value.toLowerCase());
                    console.log('nodeValue = ' + nodeValue + ' to lowercase = ' +  nodeValue.toLowerCase());
                    if(nodeValue.toLowerCase().indexOf(value.toLowerCase()) != -1) {
                        name = nodeValue;

                        var li = document.createElement('li');
                        var a = document.createElement('a');

                        a.setAttribute('class', sugguestClass);
                        a.textContent = name;
                        var url = '../product/detail.html?id=' + id;
                        a.setAttribute('href', url)

                        li.appendChild(a);

                        // push to items
                        items.push(li);
                    }
                    break;
                }
            }

            
        }

        // check have suggest tag or not, if results > 0 then update suggest tag
        // for suggest box and display suggest box, else clear suggest box and
        // not hide suggest box.
        if(items.length > 0) {
            // reset sugguest box
            suggestBox.innerHTML = "";

            // add new found item to sugguest box
            var ul = document.createElement('ul');
            var style = 'height:' + (maxDisplay * 30) + 'px;';
            style += 'overflow:hidden;';
            ul.setAttribute('style', style);
            for (var k = 0;  k < items.length;  k++) {
                // set default hover for first item
                if(k == 0) {
                    items[k].childNodes[0].setAttribute('class', sugguestClass + ' ' + hoverClass);
                }

                ul.appendChild(items[k]);
            }

            suggestBox.appendChild(ul);
            suggestBox.style.display = "block";
        } else {
            suggestBox.innerHTML = "";
            suggestBox.style.display = "none";
        }

        

    } catch (e) {
        console.log( 'Error: Document tree modified during iteration ' + e );
    }
}

/**
 * Capture event code and handle.
 */
function updateSelectedItem(e, suggestBox, sugguestClass, hoverClass, maxDisplay) {
    var keyCode = e.keyCode;
    // if key = escapse then close suggest box
    if(keyCode == 27) {
        suggestBox.innerHTML = "";
        suggestBox.style.display = "none";
        return false;
    }

    var aTags = suggestBox.getElementsByTagName('a');
    var index; // current selected item
    
    // get current hover index
    for (var i = 0; i < aTags.length; i++) {
        index = i;
        if(aTags[i].getAttribute('class').indexOf(hoverClass) != -1) {
            break;
        }
    }
    
    var currentPage = Math.floor(index / maxDisplay) + 1;

    if(e.keyCode == 40) { // key down arrow
        toggleDisplaySuggestItems(currentPage, maxDisplay, aTags, index, "down", sugguestClass, hoverClass);
        return false;
    } else if(e.keyCode == 38) { // key up arrow
        toggleDisplaySuggestItems(currentPage, maxDisplay, aTags, index, "up", sugguestClass, hoverClass);
        return false;
    } else if (e.keyCode == 13) { // enter
        if(aTags[index]) {
            document.getElementById('input-search').value = aTags[index].innerHTML;            
            aTags[index].click();
            suggestBox.innerHTML = "";
            suggestBox.style.display = "none";
        }
    }

    return true;
}

/**
 * This to check and display sugguest item.
 */
function toggleDisplaySuggestItems(currentPage, size, aTags, index, direction, sugguestClass, hoverClass) {
    var startIndex;
    var endIndex;
    var currentPosition =  index % size;
    var maxPage = Math.ceil(aTags.length / size);
    if(direction == "up") {
        if(currentPosition == 0) {
            currentPage--;
        }

        if(currentPage >= 1) {
            if(currentPosition == 0) {
                // now it's in top of page, so move cursor to bottom of page - 1
                // then set invisible page
                startIndex = currentPage * size;
                endIndex = startIndex + size;
                // disable 3 item below
                for (var i = startIndex; i < endIndex; i++) {
                    if(aTags[i]) {
                        aTags[i].setAttribute('style', 'display:none');
                    }
                }

                // show 3 items of above page
                startIndex = (currentPage - 1) * size;
                endIndex = startIndex + size;
                for (var j = startIndex; j < endIndex; j++) {
                    aTags[j].setAttribute('style', 'display:block');
                }

                if(index > 0) {
                    // hover next sugguest item below
                    aTags[index].setAttribute('class', sugguestClass);
                    aTags[index - 1].setAttribute('class', sugguestClass + ' ' + hoverClass);
                }
            }else {
                // just hover above item
                if(index > 0) {
                    aTags[index].setAttribute('class', sugguestClass);
                    aTags[index - 1].setAttribute('class', sugguestClass + ' ' + hoverClass);
                }
            }
        } 
    } else if (direction == "down") {
        if(currentPosition == size -1){
            currentPage++;
        }
        if(currentPage <= maxPage) {
            if(currentPosition == size -1) { // it's in bottom of page
                //                currentPage++;
                // now it's in bottom of page, so move cursor to top of page + 1
                // then set invisible page
                startIndex = (currentPage - 2) * size;
                endIndex = startIndex + size;
                // disable 3 item above
                for (var k = startIndex; k < endIndex; k++) {
                    aTags[k].setAttribute('style', 'display:none');
                }

                // show 3 items of below page
                startIndex = (currentPage - 1) * size;
                endIndex = startIndex + size;
                for (var l = startIndex; l < endIndex; l++) {
                    if(aTags[l]) {
                        aTags[l].setAttribute('style', 'display:block');
                    }
                }

                // hover next sugguest item below
                if(index < aTags.length - 1) {
                    aTags[index].setAttribute('class', sugguestClass);
                    aTags[index + 1].setAttribute('class', sugguestClass + ' ' + hoverClass);
                }
            } else {
                if(index < aTags.length - 1) {
                    // hover next sugguest item below
                    aTags[index].setAttribute('class', sugguestClass);
                    aTags[index + 1].setAttribute('class', sugguestClass + ' ' + hoverClass);
                }
            }
        }
    }
}

/*
 * Temporary not used.
 */
function showAddCategoryForm(xmlDoc){
    //    var nsResolver = xmlDoc.createNSResolver(xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
    var iterator = xmlDoc.evaluate('//category', xmlDoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
    
    try {
        var thisNode = iterator.iterateNext();
        while (thisNode) {
            alert( thisNode.textContent.toString() );
            thisNode = iterator.iterateNext();
        }
    }
    catch (e) {
        console.log( 'Error: Document tree modified during iteration ' + e );
    }


    var cateBox = document.getElementById('new-category-listbox');
    if(cateBox){
        var options = cateBox.getElementsByTagName('option');

        // add new option tag in first child
        var newOption = document.createElement('option');
        newOption.value = -1;
        newOption.text = "--- NONE ---";

        var newContentHTML = newOption.outerHTML + cateBox.innerHTML;
        cateBox.innerHTML = newContentHTML;

        // select current parent category to display
        for (var i = 0; i < options.length; i++) {
            if(options[i].value.trim() == cateId.trim()) {
                options[i].selected = true;
                options[i].style.background = "green";
                break;
            }
        }


    }
}

/**
 * Send request to server with new category name and parentId
 * then append new category to table in callback function.
 */
function addNewCategoryAjax() {
    try{
        var frm = document.forms.newCategoryForm;

        // validate if category name input not valid
        var inputName = document.forms.newCategoryForm.categoryName.value;
        if(inputName == "") {
            return;
        }

        var xmlHttp = getXMLObject();
        if(xmlHttp) {
            var name = frm.categoryName.value;
            var parentId = frm.parentId.value;
            var url = "../admin/addcategory.html";
            var param = 'categoryName=' + name + '&parentId=' + parentId;
            url += '?' + param;
            xmlHttp.open("POST", url, true);

            xmlHttp.send();            
            // callback function
            xmlHttp.onreadystatechange = function () {
                addNewCategoryToTableCallBack(xmlHttp);
            }
        }
    }catch (er){
        alert('Your browser does not support AJAX!');
        console.log(er);
    }
}

/**
 * Callback function of add new category, do add new row form
 * respone of a new category xml format structure.
 */
function addNewCategoryToTableCallBack(xmlHttp) {
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        // close add new category form
        document.getElementById('close-add-new-category-form').click();
        
        var rootNode = xmlHttp.responseXML;

        // check response valid or or not
        if(!rootNode || rootNode.getElementsByTagName("result")[0].textContent.trim() == "fail") {
            window.location.href = "../error/error.html";
        }

        var categoryNode = rootNode.childNodes[0];
        var id = categoryNode.attributes.getNamedItem("id").nodeValue;
        var categoryName = categoryNode.getElementsByTagName('name')[0].textContent.trim();
        
        var row = "";
        row += '<form action="../admin/updateCategory.html" method="POST" onsubmit="return false;">';
        row += '<tr class="odd">';
        row += '<textarea name="categoryId" style="display:none"><xsl:value-of select="@id" /></textarea>';
        row += '<td id="category-id">' + id + '</td>';
        row += '<td>' +  categoryName + '</td>';
        
        if(categoryNode.getElementsByTagName('parent').length == 0){
            row += '<td> </td>';
        } else {
            var parentTag =  categoryNode.getElementsByTagName('parent')[0];
            row += '<td>' + parentTag.getElementsByTagName('name')[0].textContent.trim() + '</td>';
        }

        // check to add checkbox with checked or not
        var deletedTag = categoryNode.getElementsByTagName('deleted')[0].textContent.trim();
        if(deletedTag == "true") {
            row += '<td><input id="isDeleted" type="checkbox" checked="true" disabled="disabled" /></td>';
        }else{
            row += '<td><input id="isDeleted" type="checkbox" disabled="disabled" /></td>';
        }

        // add button Update
        row += '<td><input type="submit" name="btnAction" value="Update" /></td>';

        // check to add butotn Visible or Hidden
        if(deletedTag == "true") {
            row += '<td><input type="button" onclick="deleteCategoryAjax(this);" name="btnAction" value="Visible" /></td>';
        }else {
            row += '<td><input type="button" onclick="deleteCategoryAjax(this);" name="btnAction" value="Hidden" /></td>';
        }

        row += '</tr>';
        row += '</form>';

        var table = document.getElementsByClassName('data display datatable')[0];
        var currentBody = table.getElementsByTagName('tbody')[0].innerHTML;

        // set new content for table with new row
        table.getElementsByTagName('tbody')[0].innerHTML = currentBody + row;

        // reset value for add new category form
        document.forms.newCategoryForm.categoryName.value = "";

        console.log('Add new category to table successfully');
    }else{
        console.log('Could not get response form server! Try again!');

        // refresh current page
        //        window.location = '../admin/category.html';
        document.getElementById('close-add-new-category-form').click();
    }
}

////////////// ORDER PAGE /////////////////////

/**
 * when user click on order row then display update form.
 */
function displayUpdateOrderForm(tr) {
    try {
        var id = tr.getElementsByTagName('td')[0].innerHTML.trim();

        // set value for updateOrderForm
        document.getElementById('update-order-form-id').innerHTML = id;
        
        // format mm-dd-yyyy
        var sDate = document.getElementById('row-order-deliveredDatetime' + id).innerHTML.trim();
        var a = sDate.split('-');
        // format yyyy-mm-dd
        var newDate = a[2] + '-' + a[0] + '-' + a[1];

        document.getElementById('update-order-form-delivereddate').getElementsByTagName('input')[0].value = newDate;
        // treat as display update order form
        document.getElementById('update-order-anchor').click();
    }
    catch(ex) {
        console.log(ex);
    }

}

/**
 * Send order update information to server using asynchronous type.
 */
function updateOrderAjax() {
    var xmlHttp = getXMLObject();
    if(xmlHttp) {
        try{
            var orderId = document.getElementById('update-order-form-id').innerHTML.trim();
            var orderStatusId = document.forms.updateOrderForm.orderStatusId.value;
            var deliveredDate = document.forms.updateOrderForm.delivereddate.value;
            var orderStatusListBox = document.getElementById('update-order-form-status-listbox');
            var orderStatusValue = orderStatusListBox.options[orderStatusListBox.selectedIndex].innerHTML.trim();

            var url = '../admin/updateOrder.html?orderId=' + orderId + '&orderStatusId=' + orderStatusId + '&delivereddate=' + deliveredDate;

            xmlHttp.open("POST", url, true);
            xmlHttp.send();

            // callback function
            xmlHttp.onreadystatechange = function () {
                updateOrderTableCallBack(xmlHttp, orderId, deliveredDate, orderStatusValue);
            }
        }catch(ex) {
            alert('Your browser does not support AJAX!');
            console.log(ex);
        }
    }
}

function updateOrderTableCallBack(xmlHttp, orderId, deliveredDate, orderStatusValue) {
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var result = xmlHttp.responseText;
        if(result) {
            // update order table for orderId row
            if(result.trim() == "success") {
                var a = deliveredDate.split('-');
                var formatDate = "";
                if(a.length == 3) {
                    formatDate = a[2] + '-' + a[1] + '-' + a[0];
                }

                document.getElementById('row-order-deliveredDatetime' + orderId).innerHTML = formatDate;
                document.getElementById('row-orderstatus-description' + orderId).innerHTML = orderStatusValue;
                document.getElementById('update-order-form-close').click();
            } else {
                window.location.href = "../error/error.html";
            }
        } else {
            console.log('handle in server has error!! in updateOrderTableCallBack()')
        }
    }else {
        console.log("Still can't get response from sever in updateOrderTableCallBack()");
    }
}

/**
 * Search order confirmation number when user fill confirmation number then enter
 */
function searchConfirmation(e) {
    if (e.keyCode == 13) { // enter key code
        var confirmation = document.getElementById("txtSearchConfirmation").value.trim();
        if(confirmation == "") { // no need to search
            return;
        }

        var xmlHttp = getXMLObject();
        if(xmlHttp) {
            try {
                var url = '../admin/searchOrder.html?confirmation=' + confirmation;
                xmlHttp.open('POST', url, true);
                xmlHttp.send();

                xmlHttp.onreadystatechange = function() {
                    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                        var response = xmlHttp.responseXML;
                        updateOrderTableAfterSearchCallBack(response);
                    } else {
                        console.log("Still can't get response from sever");
                    }
                }
            }catch(er){
                alert('Your browser does not support AJAX!');
                console.log(er);
            }
        }
    }
}

function searchOrderCriteria() {
    var xmlHttp = getXMLObject();
    if(xmlHttp) {
        try {
            var fromDate = document.getElementById('input-search-order-from').value.trim();
            var toDate = document.getElementById('input-search-order-to').value.trim();
            var orderStatusListBox = document.getElementById('search-order-form-status-listbox');
            var orderStatusValue = orderStatusListBox.options[orderStatusListBox.selectedIndex].value.trim();
            var url = '../admin/searchOrder.html';

            var params = new Array();
            if(fromDate != "") {
                params.push('fromDate=' + fromDate);
            }
            
            if(toDate != "") {
                params.push('toDate=' + toDate);
            }

            if(Number(orderStatusValue) != -1) {
                params.push('orderStatus=' + orderStatusValue);
            }

            var content = params.join('&');

            xmlHttp.open("POST", url, true);
            xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttp.send(content);

            xmlHttp.onreadystatechange = function () {
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    updateOrderTableAfterSearchCallBack(xmlHttp.responseXML);
                } else {
                    console.log("Still can't get response from sever");
                }
            }

        }catch(er){
            alert('Your browser does not support AJAX!');
            consolse.log(er);
        }
    }
}

/**
 * Update order table content after search, travel DOM tree.
 */
function updateOrderTableAfterSearchCallBack(xmldoc) {
    if(!xmldoc) {
        console.log('Response null in updateOrderTableAfterSearchCallBack()');
        document.getElementById('order-table').getElementsByTagName('tbody')[0].innerHTML = "";
        return;
    }

    if(xmldoc){
        if(xmldoc.getElementsByTagName('result').length > 0) {
            if (xmldoc.getElementsByTagName('result')[0].textContent.trim() == "noresult") {
                alert('No order was found!');
            } else if(xmldoc.getElementsByTagName('result')[0].textContent.trim() == "error") {
                window.location.href = "../error/error.html";
            }
        }


        var orderTableContentHTML = ""
        var orderList = xmldoc.getElementsByTagName('order');
        if (orderList.length > 0) {
            var tr = "";
            var order;
            var orderId;
            for (var i = 0;  i < orderList.length;  i++) {
                order = orderList[i];
                orderId = order.attributes.getNamedItem("id").nodeValue.trim();
                tr += '<tr class="odd" onclick="displayUpdateOrderForm(this);" >';
                tr += '<td id="row-order-id' + orderId + '">' + orderId + "</td>";
                tr += '<td id="row-order-confirmationString">' + order.getElementsByTagName('confirmation')[0].textContent + "</td>";
                tr += '<td id="row-order-username">' + order.getElementsByTagName('user')[0].textContent + "</td>";
                tr += '<td id="row-order-placedDate' + orderId + '">' + order.getElementsByTagName('placedDate')[0].textContent + "</td>";
                tr += '<td id="row-order-deliveredDatetime' + orderId + '">' + order.getElementsByTagName('deliveredDate')[0].textContent + "</td>";
                tr += '<td>' + order.getElementsByTagName('amount')[0].textContent + "</td>";
                tr += '<td id="row-orderstatus-description' + orderId + '">' + order.getElementsByTagName('orderstatus')[0].textContent + "</td>";
                tr += '<td><a href="../admin/orderDetail.html?orderId=' + orderId + '" class="custom-button" onclick="event.preventBubble();">Detail</a> </td>';
                tr += "</tr>";

                orderTableContentHTML += tr;
                tr = "";
            }
        }

        // update table
        document.getElementById('order-table').getElementsByTagName('tbody')[0].innerHTML = orderTableContentHTML;
    } else {
        alert('No result found!')
        console.log('respone null in updateOrderTableAfterSearchCallBack()')
    }
}

//Send dom to server
//Created Date : 31/3/2013
//Version 0.1
function sendDomToServer(inputStream, url, callbackfunction, updatedUser) {
    var xmlHttp = getXMLObject();
    var stringUpdatedUser = "";

    for (var i = 0; i < updatedUser.length; i++) {
        stringUpdatedUser += (updatedUser[i] + ",");
    }
    var resultStream = '&resultStream='+ (new XMLSerializer()).serializeToString(inputStream) + "&updatedUser=" + stringUpdatedUser;

   
    xmlHttp.open("POST", url, false);

    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

       
    xmlHttp.onreadystatechange = function() {
        callbackfunction(xmlHttp);
    }
    
    xmlHttp.send(resultStream);

}